#!/usr/bin/perl
# 2012/12/10 Make conversion table used for combination to distance

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0  -i [Hind III sites file] -o [conversion table]\n";
}


my %opt;
getopts("i:o:", \%opt);
my $FILE_HINDIII = $opt{i};
my $FILE_table = $opt{o};


### read Hind III middle sites
my @Hinds;
my %MAX_chr = ('chr1'=>0, 'chr2'=>0, 'chr3'=>0);
{
	my $fh_in = IO::File->new($FILE_HINDIII) or die "cannot open $FILE_HINDIII: $!";
	while($_ = $fh_in->getline()){
		if(m/^#/){
			next;
		}
		s/\r?\n//;
		my ($number, $chr, $pos, $before, $after) = split /\t/;

		my $middleL = $pos - int($before / 2);
		my $middleR = $pos + int($after / 2);

		my $nameL = $number . "L";
		my $nameR = $number . "R";
		push @Hinds, [$nameL, $chr, $middleL];
		push @Hinds, [$nameR, $chr, $middleR];
	}
	$fh_in->close();
}


my $fh_out = IO::File->new($FILE_table, 'w') or die "cannot write $FILE_table: $!";
my $interNUM = 0;
for(my $i = 0; $i < @Hinds; $i++){
	my ($name1, $chr1, $pos1) = @{$Hinds[$i]};
	for(my $j = $i+1; $j < @Hinds; $j++){
		my ($name2, $chr2, $pos2) = @{$Hinds[$j]};

		if($chr1 ne $chr2){
			$interNUM++;
			next;
		}

		my $distance = abs($pos1 - $pos2);

		$fh_out->print("$name1\t$name2\t$distance\n");
	}
}
$fh_out->close();

print "$interNUM\n";

